<?php
/**
 * Created by PhpStorm.
 * User: littleboy
 * Date: 18.12.25
 * Time: 22:38
 */

namespace app\admin\logic;
use Exception;
use think\exception\ErrorException;

/**
 * Class LifeAccount
 * 生活号逻辑
 * @package app\admin\logic
 */
class LifeAccount extends AdminBase
{
    /**
     * 获取生活号列表
     */
    public function lifeAccountList($where = [], $field = true, $order = '')
    {
        // 指定数据库表别名
        $this->modelLifeAccount->alias('m');

        // 条件
        $where['m.id'] = ['<>', 0];

        // 查数据库
        $list = $this->modelLifeAccount->getList($where, $field, $order);

//        foreach ($list as $key => $value) {
//            try
//            {
//                $value['totalFans'] = $this->getLifeAccountFans($value);
//                $this->modelLifeAccount->setInfo($value);
//            } catch (ErrorException $e)
//            {
//                echo "填写的生活号信息不正确!";
//                $value['status'] = -1;
//                $this->modelLifeAccount->setInfo($value);
//            }
//        }
        return $list;
    }

    /**
     * 导出excel
     */
    public function dataExport()
    {
        $list = $this->modelLifeAccount->getList();

        $titles = "生活号名,appid,粉丝数量,生活号状态";

        $keys   = "life_name,appid,totalFans,carriage_status";

        export_excel($titles, $keys, $list, '生活号列表');
    }


    /**
     * 获取生活号粉丝列表
     * @param $lifeAccount 生活号参数
     * @param $next_user_id 下一个user_id
     * @return \SimpleXMLElement 粉丝总数
     */
    public function getLifeAccountFans($lifeAccount, $next_user_id = "")
    {
        vendor('alipay.aop.AopClient');
        vendor('alipay.aop.request.AlipayOpenPublicFollowBatchqueryRequest');
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipaydev.com/gateway.do';

        $aop->appId = $lifeAccount['appid'];
        $aop->rsaPrivateKey = $lifeAccount['merchant_private_key'];
        $aop->alipayrsaPublicKey = $lifeAccount['alipay_public_key'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayOpenPublicFollowBatchqueryRequest ();

        // 如果有下一个user_id
        if ($next_user_id != "")
        {
            $request->setBizContent($next_user_id);
        }

        // 序列化结果json
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

        // 获取总粉丝数
        $resultCount = $result->$responseNode->count;

        // 如果大于一万, 则再次拉取粉丝数
        if ($resultCount >= 10000)
        {
            $next_user_id = $result->$responseNode->next_user_id;
            $resultCount += $this->getLifeAccountFans($lifeAccount, $next_user_id);
        }
        return $resultCount;
    }

    /**
     * 获取生活号列表过滤
     */
    public function getLifeAccountListFilter($param = [])
    {

        $where = [];

        // 获取页面中用户点击的条件
        $group = empty($param['group']) ? DATA_DISABLE : (int)$param['group'];

        // group条件
        !empty($group) && $where['life_type_id'] = $group;

        // 排序
//        $sort = 'sort asc, create_time desc';

        // 用户点击的排序
        if (!empty($param['order_field'])) {

//            $sort = empty($param['order_val']) ? $param['order_field'] . ' asc' : $param['order_field'] . ' desc';
        }

        foreach ($where as $key => $val) {
            echo $key . ' => ' . $val;
        }

        // 封装, list 过滤后的列表 group 条件
        $data['list'] = $this->lifeAccountList($where, true);

        $data['group'] = $group;

        return $data;
    }

    /**
     * 添加生活号
     * @param array $data
     * @return array
     */
    public function addLifeAccount($data = [])
    {
        // 检查是否包含所需要的全部字段
        $validate_result = $this->validateLifeAccount->scene('add')->check($data);

        // 如果验证未通过
        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateLifeAccount->getError()];
        }

        // 验证通过
        $url = url('lifeAccountList');

        //
        $result = $this->modelLifeAccount->setInfo($data);

        $result && action_log('新增', '生活号，life_name：' . $data['life_name']);

        return $result ? [RESULT_SUCCESS, '生活号添加成功', $url] : [RESULT_ERROR, $this->modelLifeAccount->getError()];
    }

    /**
     *
     */
    public function updateLifeAccount($data = []){
        // 检查是否包含所需要的全部字段
        $validate_result = $this->validateLifeAccount->scene('add')->check($data);

        // 如果验证未通过
        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateLifeAccount->getError()];
        }

        // 验证通过
        $url = url('lifeAccountList');

        $result = $this->modelLifeAccount->setInfo($data);

        $result && action_log('新增', '生活号，life_name：' . $data['life_name']);

        return $result ? [RESULT_SUCCESS, '生活号添加成功', $url] : [RESULT_ERROR, $this->modelLifeAccount->getError()];
    }


    /**
     * 上架和下架
     * @return array|\SimpleXMLElement
     * @throws \Exception
     */
    public function changeStatus($param = [], $where = [], $field = true) {
        if (empty($param)) {
            return [RESULT_ERROR, '非法操作'];
        }
        $ids = (int)$param['ids'];
        $status = (int)$param['status'];
//        dump($ids);
//        dump($status);
//        $this->modelLifeAccount->alias('m');
        $where['id'] = ['=', $ids];
        $result = $this->modelLifeAccount->updateInfo($where, ['status', $status]);
        return $result ? [RESULT_SUCCESS, '删除成功'] : [RESULT_ERROR, $this->modelBlogroll->getError()];
    }

    /**
     * @param array $param
     * 获取单条数据
     */
    public function getOne($param = [], $where = [], $field = true) {
        if (empty($param)) {
            return [RESULT_ERROR, '非法操作'];
        }
        $ids = (int)$param['ids'];
        // 指定数据库表别名
        $this->modelLifeAccount->alias('m');
        // 条件
        $where['m.id'] = ['=', $ids];
        // 查数据库获取数据
        $lifeAccount = $this->modelLifeAccount->getInfo($where, $field);
        return $lifeAccount;
    }


    /**
     * @function 删除生活号
     */
    public function deleteLifeAccount($param = [], $where = []) {
        if (empty($param)) {
            return [RESULT_ERROR, '非法操作'];
        }
        $ids = (int)$param['ids'];
        // 指定数据库表别名
        $this->modelLifeAccount->alias('m');
        // 条件
        $where['m.id'] = ['=', $ids];
        // 查数据库获取数据
        $result = $this->modelLifeAccount->deleteInfo($where);
        $result && action_log('删除', '生活号删除' . '，where：' . http_build_query($where));

        return $result ? [RESULT_SUCCESS, '删除成功'] : [RESULT_ERROR, $this->modelBlogroll->getError()];

    }

    /**
     * @function 获取生活号基本信息
     */
    public function getLifeAccountInfo($param = [], $where = []) {
        if (empty($param)) {
            return [RESULT_ERROR, '非法操作'];
        }
        $ids = (int)$param['ids'];
        // 指定数据库表别名
        $this->modelLifeAccount->alias('m');
        // 条件
        $where['m.id'] = ['=', $ids];
        // 查数据库获取数据
        $lifeAccount = $this->modelLifeAccount->getInfo($where);

        vendor('alipay.aop.AopClient');
        vendor('alipay.aop.request.AlipayOpenPublicInfoQueryRequest');

        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $lifeAccount['appid'];
        $aop->rsaPrivateKey = $lifeAccount['merchant_private_key'];
        $aop->alipayrsaPublicKey = $lifeAccount['alipay_public_key'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayOpenPublicInfoQueryRequest ();
        $result = $aop->execute ( $request);
        dump($result);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return $result->$responseNode;
        } else {
            return '';
        }

    }

}
